/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.amuthu.parser;

import java.text.ParseException;
import org.amuthu.expression.Expression;
import org.amuthu.expression.ExpressionFactory;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.amuthu.QuoteDataStore;
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RuleReturnScope;

/**
 *
 * @author prabhu
 */
public class ExpressionEvaluator
{
   private  String expression;

   public ExpressionEvaluator(String expression)
   {
      this.expression = expression;
   }

   protected CommonTree parse(String expression)
   {
      AmuthuLexer lexer = new AmuthuLexer(new ANTLRStringStream(expression));
      AmuthuParser parser = new AmuthuParser(new CommonTokenStream(lexer));

      try
      {
         RuleReturnScope rule = parser.expression();
         return (CommonTree) rule.getTree();
      }
      catch (RecognitionException ex)
      {
         Logger.getLogger(ExpressionEvaluator.class.getName()).log(Level.SEVERE, null, ex);
      }

      return null;
   }

   public double computeExpression()
   {
      EvaluationVisitor visitor = new EvaluationVisitor(QuoteDataStore.getInstance());
      CommonTree tree = parse(expression);

      try
      {
         Expression expr = ExpressionFactory.create(tree);
//         System.out.println(expr.toString());

         expr.accept(visitor);
      }
      catch (NumberFormatException ex)
      {
         Logger.getLogger(ExpressionEvaluator.class.getName()).log(Level.SEVERE, null, ex);
      }
      catch (ParseException ex)
      {
         Logger.getLogger(ExpressionEvaluator.class.getName()).log(Level.SEVERE, null, ex);
      }


      return visitor.getResult();
   }

   public int computeDayDependency()
   {
      DayDependencyVisitor visitor = new DayDependencyVisitor(QuoteDataStore.getInstance());
      CommonTree tree = parse(expression);

      try
      {
         Expression expr = ExpressionFactory.create(tree);

         expr.accept(visitor);
      }
      catch (NumberFormatException ex)
      {
         Logger.getLogger(ExpressionEvaluator.class.getName()).log(Level.SEVERE, null, ex);
      }
      catch (ParseException ex)
      {
         Logger.getLogger(ExpressionEvaluator.class.getName()).log(Level.SEVERE, null, ex);
      }

      return 0;
   }
}
